// index.js

const appInstance = getApp()
const uploadUrl = appInstance.globalData.request_url + 'api/upload_files'  
const uploadPromises = []
Component({
  data: {
    activeValues: [0],
    order_data_list:[],
    color:'red',
    display_tempFiles:false,
    tempFilePaths:[],
    filtertempFilePaths:[]
  },
  methods:{
    payment_order(e){
      let order_id = e.currentTarget.dataset.id
      let that = this
      that.upload_file(order_id)
      that.get_order_data(e).then(res => {
        // console.log(res)
        // that.modify_order(res)
        that._payment_order(res)
      }).catch(err => {
        console.log(err)
        wx.showToast({
          title: '支付失败',
          icon: 'error',
          duration: 2000
        })
      })
 
    },
    _payment_order(res){
      let that = this
      wx.requestPayment({
        timeStamp: res.timeStamp,
        nonceStr: res.nonceStr,
        package: 'prepay_id=' + res.package,
        signType: 'RSA',
        paySign: res.paySign,
        success (res) {
          that.onShow()
         },
        fail (err) { 
          // 有可能下单的时间戳和实际支付的时间戳相差很多，导致支付报错
          console.log('pay err', err)
          wx.showToast({
            title: '支付失败',
            icon: 'error',
            duration: 2000
          })
        }
      })
    },
    bindViewTap() {
      wx.navigateTo({
        url: '../logs/logs'
      })
    },
    handleChange(e) {
      console.log(e)
      this.setData({
        activeValues: e.detail.value,
      });
    },
    onShow(){
      let url = appInstance.globalData.request_url + 'api/query/order'
      let data = {}
      let that = this
      wx.login({
        success: (res) => {
          wx.request({
            url:url,
            data:Object.assign({wx_code:res.code},data),
            method:'GET',
            success(resp){
              let msg = resp.data.msg
              let status = resp.data.status
              let data = resp.data.data
              if (status != 200){
                console.log('失败')
              }else{
                that.setData({order_data_list:data})
              }
            },
            fail(err){
              console.log(err)
            }
          })
        },
      })

    },
    change_corporate_phone_number(e){
      console.log(e)
      let corporate_phone_number = e.detail.value
      let order_id = e.currentTarget.dataset.id
      let order_data_list = this.data.order_data_list
      let that = this
      order_data_list.forEach((item) => {
          if(order_id == item.id){
            item.corporate_phone_number = corporate_phone_number
          }
      })
      that.setData({order_data_list:order_data_list})
    },
    change_corporate_id_card(e){
      console.log('触发！！！')
      let corporate_id_card = e.detail.value
      let order_id = e.currentTarget.dataset.id
      let order_data_list = this.data.order_data_list
      let that = this
      order_data_list.forEach((item) => {
          if(order_id == item.id){
            item.corporate_id_card = corporate_id_card
          }
      })
      that.setData({order_data_list:order_data_list})
    },
    get_order_data(e){
      let order_id = e.currentTarget.dataset.id
      let order_data_list = this.data.order_data_list
      return new Promise(function (resolve, reject){
        order_data_list.forEach((item) => {
          if(order_id == item.id){
            resolve(item)
          }
      })
      })
    },
    modify_order(e){
      let that = this
      that.get_order_data(e).then(res => {
        // console.log(res)
        that._modify_order(res)
      }).catch(err => {
        console.log(err)
        wx.showToast({
          title: '订单异常',
          icon: 'error',
          duration: 2000
        })
      })
    },
    _modify_order(item){
      let url = appInstance.globalData.request_url + 'api/modify/order'
      let data = {
        'order_data':item
      }
      let that = this
      wx.login({
        success: (res) => {
          wx.request({
            url:url,
            data:Object.assign({wx_code:res.code},data),
            method:'POST',
            success(resp){
              let msg = resp.data.msg
              let status = resp.data.status
              let data = resp.data.data
              if (status != 200){
                console.log('失败')
              }else{
                that.setData({order_data_list:data})
              }
            },
            fail(err){
              console.log(err)
            }
          })
        },
      })
    },
    sleep(ms, callback) {
      setTimeout(callback, ms);
    },
    choose_files(e){
      let that = this
      let order_id = e.currentTarget.dataset.id
      wx.chooseMessageFile({
        count: 10,
        type: 'all',
        success (res) {
          console.log(res)
          res.tempFiles.forEach((item) => {
            item.order_id = order_id
          })
          let tempFiles = res.tempFiles
          // tempFilePath可以作为img标签的src属性显示图片
          console.log(res.tempFiles)
          // that.setData({tempFilePaths:res.tempFiles, upload_vsible:true})
          that.setData({tempFilePaths:tempFiles})
        }
      })
    },

    upload_file(order_id){
      if (this.data.tempFilePaths){
        this.data.tempFilePaths.forEach((file) => {
          const uploadPromise = new Promise((resolve, reject) => {
            console.log('订单id' + order_id)
            wx.uploadFile({
              url: uploadUrl,
              filePath: file.path,
              formData:{
                'file_name':file.name,
                'order_id':order_id?order_id:null,
              },
              name: 'file',
              success: (res) => {
                resolve(res.data);
              },
              fail: (error) => {
                reject(error);
              }
            });
          });
          
          // 将每个上传请求Promise添加到数组中
          uploadPromises.push(uploadPromise);
        });
      }
   
      
      // 使用Promise.all并行发送所有上传请求
      Promise.all(uploadPromises)
        .then((responses) => {
          console.log('所有上传请求成功:', responses);
        })
        .catch((errors) => {
          console.error('上传请求中出现错误:', errors);
        });
    },

    display_tempFiles(e){
      console.log(111111111111111111111)
      console.log(e)
      let order_id = e.currentTarget.dataset.id
      let tempFilePaths = this.data.tempFilePaths
      let filtertempFilePaths = []
      if (tempFilePaths.length){
        tempFilePaths.forEach((item) => {
          if(item.order_id == order_id){
            filtertempFilePaths.push(item)
          }
        })
        if (filtertempFilePaths.length){
          this.setData({display_tempFiles:true,filtertempFilePaths:filtertempFilePaths})
        }else{
          wx.showToast({
            title: '未上传材料',
            icon: 'error',
            duration: 2000
          })
        }
      }else{
        wx.showToast({
          title: '未上传材料',
          icon: 'error',
          duration: 2000
        })
      }
    },
    onVisibleChange(e) {
      this.setData({
        display_tempFiles: e.detail.visible,
      });
    },
    delete_attachment(e){
      let tempFilePaths = this.data.tempFilePaths
      let filtertempFilePaths = this.data.filtertempFilePaths
      let delete_index = e.currentTarget.dataset.id
      let that = this
      tempFilePaths.forEach(function(item, index) {
        if (index == delete_index){
          tempFilePaths.splice(delete_index, 1)
          that.setData({tempFilePaths:tempFilePaths})
        }
      });
      filtertempFilePaths.forEach(function(item, index) {
        if (index == delete_index){
          filtertempFilePaths.splice(delete_index, 1)
          that.setData({filtertempFilePaths:filtertempFilePaths})
        }
      });
    }


  },

})
